{
 "cells": [
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "# 低方差过滤法",
   "id": "5016fb2cbdf9d5e2"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-10-08T05:26:39.801537Z",
     "start_time": "2025-10-08T05:26:38.063951Z"
    }
   },
   "cell_type": "code",
   "source": [
    "import numpy as np\n",
    "from sklearn.feature_selection import VarianceThreshold"
   ],
   "id": "b0e2756e3a1f2711",
   "outputs": [],
   "execution_count": 1
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-10-08T05:29:18.697401Z",
     "start_time": "2025-10-08T05:29:18.694891Z"
    }
   },
   "cell_type": "code",
   "source": [
    "vt = VarianceThreshold(0.01) # 设置方差阈值\n",
    "X = np.random.normal(0, 1, 100) # 生成100个均值为0，标准差为1的正态分布随机数\n",
    "print(X.shape)\n",
    "print(X.var())"
   ],
   "id": "1e4b9e5ccb3d6bea",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "(100,)\n",
      "0.9735218867549701\n"
     ]
    }
   ],
   "execution_count": 14
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-10-08T05:30:58.639052Z",
     "start_time": "2025-10-08T05:30:58.636052Z"
    }
   },
   "cell_type": "code",
   "source": [
    "X_new = X * 0.1 # 将X的值缩小10倍，方差缩小100倍\n",
    "print(X_new.var())\n",
    "\n",
    "Y = np.vstack((X, X_new)).T # 将X和X_new按列堆叠，形成一个二维数组\n",
    "print(Y.shape)"
   ],
   "id": "8ba9368a42225570",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0.009735218867549703\n",
      "(100, 2)\n"
     ]
    }
   ],
   "execution_count": 16
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-10-08T05:31:40.571818Z",
     "start_time": "2025-10-08T05:31:40.568391Z"
    }
   },
   "cell_type": "code",
   "source": [
    "Y_new = vt.fit_transform(Y)\n",
    "print(Y_new.shape) # 只有一列被保留下来"
   ],
   "id": "7884a3b4f422e00e",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "(100, 1)\n"
     ]
    }
   ],
   "execution_count": 17
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
